package com.xquant.trade.report.service.impl;

import com.github.pagehelper.PageInfo;
import com.xquant.common.core.constant.Constants;
import com.xquant.common.core.constant.ErrMsgConstant;
import com.xquant.common.core.constant.SummitTranConstants;
import com.xquant.common.core.exception.ServiceException;
import com.xquant.common.core.text.Convert;
import com.xquant.common.core.web.page.TableDataInfo;
import com.xquant.common.redis.service.RedisService;
import com.xquant.trade.utils.ResponseVo;
import com.xquant.trade.report.entity.OpexMonitor;
import com.xquant.trade.report.entity.OpexMonitorDetail;
import com.xquant.trade.report.mapper.OpexMonitorMapper;
import com.xquant.trade.report.service.OpexMonitorService;
import com.xquant.trade.trade.mapper.TequityStructureMapper;
import com.xquant.trade.trade.mapper.TradeMapper;
import com.xquant.trade.utils.DateUtils;

import com.xquant.common.core.utils.file.CompressUtils;
import com.xquant.trade.utils.SysUtils;
import com.xquant.system.api.RemoteLogService;
import com.xquant.system.api.domain.TsysInterfaceLog;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.SQLException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @Auther: B946
 * @Date: 10/03/2020 15:24
 * @Description:
 */
@Service(OpexMonitorService.BEAN_NAME)

public class OpexMonitorServiceImpl implements OpexMonitorService {

    private static Logger logger = LoggerFactory.getLogger(OpexMonitorServiceImpl.class);

    @Autowired
    private OpexMonitorMapper opexMonitorMapper;

    @Value("${summit.filePath}")
    private String summitFileDir;

    @Value("${summit.zipFilePath}")
    private String zipFilePath;

    @Autowired
    private TradeMapper tradeMapper;

    @Autowired
    private TequityStructureMapper tequityStructureMapper;

    @Autowired
    private RemoteLogService remoteLogService;

    @Autowired
    private RedisService redisService;

    @Override
    public PageInfo<OpexMonitor> queryOpexMonitorList(OpexMonitor params) {
        List<OpexMonitor> list = null;
        try {
            list = opexMonitorMapper.queryOpexMonitor(params);
        } catch (SQLException sqlException) {
            sqlException.printStackTrace();
        }
        return new PageInfo<OpexMonitor>(list);
    }

    @ResponseBody
    @RequestMapping(value = "/queryOpexMonitorDetailList.action")
    public PageInfo<OpexMonitorDetail> queryOpexMonitorDetailList(OpexMonitorDetail params) {
        List<OpexMonitorDetail> list = null;
        try {
            list = opexMonitorMapper.queryOpexMonitorDetailList(params);
        } catch (SQLException sqlException) {
            sqlException.printStackTrace();
        }

        if (params.getOpexType().equals("dailyPrice")) {
            for (OpexMonitorDetail opexMonitorDetail : list) {
                opexMonitorDetail.setiCode(opexMonitorDetail.getDetCode().split(",")[0]);
            }
        }

        if (params.getOpexType().equals("initPrice")) {
            for (OpexMonitorDetail opexMonitorDetail : list) {
                String context = opexMonitorDetail.getDetContext();
                String[] split = context.split(",");
                opexMonitorDetail.setExtTradeId(split[0]);
                opexMonitorDetail.setiCode(split[1]);
                opexMonitorDetail.setpType(split[2]);
                opexMonitorDetail.setTradeDate(split[3]);
                opexMonitorDetail.setuICode(split[4]);
                opexMonitorDetail.setuIName(split[5]);
                opexMonitorDetail.setSpotPrice(split[6]);
            }
        }

        if (params.getOpexType().equals("endDayValuation")) {
            for (OpexMonitorDetail opexMonitorDetail : list) {
                String context = opexMonitorDetail.getDetContext();
                String[] split = context.split(",");
                opexMonitorDetail.setExtTradeId(split[0]);
                opexMonitorDetail.setiCode(split[1]);
                opexMonitorDetail.setpType(split[2]);
                opexMonitorDetail.setTradeDate(split[3]);
                opexMonitorDetail.setuICode(split[4]);
                opexMonitorDetail.setuIName(split[5]);
            }
        }
        return new PageInfo<OpexMonitorDetail>(list);
    }

    @Override
    public ResponseVo checkOpexMonitor(Map<String, Object> params) {
        ResponseVo dailyResp = checkDailyPrice(params);
        if (dailyResp.getErrorCode() == -1) {
            return dailyResp;
        }
        ResponseVo curveResp = checkCurve(params);
        if (curveResp.getErrorCode() == -1) {
            return curveResp;
        }
        ResponseVo summitResp = checkSummitFile(params);
        if (summitResp.getErrorCode() == -1) {
            return summitResp;
        }
        ResponseVo initPriceResp = checkSpotPrice(params);
        if (initPriceResp.getErrorCode() == -1) {
            return initPriceResp;
        }
        ResponseVo calcResp = checkCalc(params);
        if (initPriceResp.getErrorCode() == -1) {
            return calcResp;
        }
        return ResponseVo.success();
    }

    @Override
    public ResponseVo checkDailyPrice(Map<String, Object> params) {
        String configKey = Constants.SYS_CONFIG_KEY + "opexMonitor-dailyprice";
        String configValue = Convert.toStr(redisService.getCacheObject(configKey));

        if (!configValue.isEmpty()) {
            params.put("range", configValue);
        }

        ResponseVo responseVo = new ResponseVo();
        OpexMonitor opexMonitor = new OpexMonitor();
        try {
            int ict = configValue.split(",").length;
            int dct = opexMonitorMapper.queryDailyPriceCount(params);

            opexMonitor.setOpexDate(MapUtils.getString(params, "opexDate"));
            opexMonitor.setOpexName("行情检查");
            opexMonitor.setOpexType("dailyPrice");
            opexMonitor.setUpdateTime(DateUtils.getCurr_YYYY_MM_DD_HH_MM_SS_SSS());
            if (dct < ict) {
                opexMonitor.setStatus("0");
                opexMonitor.setOpexMsg("行情缺失");
            } else {
                opexMonitor.setOpexMsg("行情正常");
                opexMonitor.setStatus("1");
            }
            if (opexMonitorMapper.queryOpexMonitor(opexMonitor).size() > 0) {
                opexMonitorMapper.updateOpexMonitor(opexMonitor);
            } else {
                opexMonitorMapper.insertOpexMonitor(opexMonitor);
            }
            if (dct < ict) {
                opexMonitor.setRange(configValue);
                opexMonitorMapper.deleteOpexMonitorDetail(opexMonitor);
                //检查系统参数的标的数据是否存在
                checkInstrument(configValue, opexMonitor);

                opexMonitorMapper.insertOpexMonitorDetailDaily(opexMonitor);
            }
            responseVo.setErrorCode(0);
        } catch (SQLException sqlException) {
            responseVo.setErrorCode(-1);
            responseVo.setErrorMsg("行情检查失败!");
            throw new ServiceException("行情检查失败!");
        }
        return responseVo;
    }

    @Override
    public ResponseVo checkCurve(Map<String, Object> params) {
        ResponseVo responseVo = new ResponseVo();
        try {
            checkIrCurve(params);
            checkDivCurve(params);
            checkVlsCurve(params);
            responseVo.setErrorCode(0);
        } catch (SQLException sqlException) {
            responseVo.setErrorCode(-1);
            responseVo.setErrorMsg("曲线曲面检查失败!");
            throw new ServiceException("曲线曲面检查失败!");
        }
        return responseVo;
    }

    public void checkInstrument(String instrumentList, OpexMonitor opexMonitor) {
        String[] instruments = instrumentList.split(",");
        for (String instrument : instruments) {
            String[] iCodes = instrument.split("-");
            HashMap<String, Object> map = new HashMap<>();
            map.put("iCode", iCodes[0]);
            map.put("aType", iCodes[1]);
            map.put("mType", iCodes[2]);
            map.put("opexType", opexMonitor.getOpexType());
            map.put("opexDate", opexMonitor.getOpexDate());
            map.put("status", opexMonitor.getStatus());
            try {
                opexMonitorMapper.checkInstrument(map);
            }catch (SQLException e) {
                throw new ServiceException(ErrMsgConstant.INSERT_ERRINFO);
            }
        }
    }

    @Override
    public void checkIrCurve(Map<String, Object> params) throws SQLException {
        String configKey = Constants.SYS_CONFIG_KEY + "opexMonitor-ircurve";
        String configValue = Convert.toStr(redisService.getCacheObject(configKey));

        if (!configValue.isEmpty()) {
            params.put("range", configValue);
        }

        OpexMonitor opexMonitor = new OpexMonitor();
        //利率曲线检查
        int ict = opexMonitorMapper.queryIrCurveCount(params);
        int dct = opexMonitorMapper.queryIrCurveRatesCount(params);

        opexMonitor.setOpexDate(MapUtils.getString(params, "opexDate"));
        opexMonitor.setOpexName("利率曲线检查");
        opexMonitor.setOpexType("irCurve");
        opexMonitor.setUpdateTime(DateUtils.getCurr_YYYY_MM_DD_HH_MM_SS_SSS());
        if (dct < ict) {
            opexMonitor.setStatus("0");
            opexMonitor.setOpexMsg("利率曲线结果缺失");
        } else {
            opexMonitor.setOpexMsg("利率曲线结果正常");
            opexMonitor.setStatus("1");
        }
        if (opexMonitorMapper.queryOpexMonitor(opexMonitor).size() > 0) {
            opexMonitorMapper.updateOpexMonitor(opexMonitor);
        } else {
            opexMonitorMapper.insertOpexMonitor(opexMonitor);
        }
        if (dct < ict) {
            opexMonitor.setRange(configValue);
            opexMonitorMapper.deleteOpexMonitorDetail(opexMonitor);
            opexMonitorMapper.insertOpexMonitorDetailIrCurve(opexMonitor);
        }
    }

    @Override
    public void checkDivCurve(Map<String, Object> params) throws SQLException {
        String configKey = Constants.SYS_CONFIG_KEY + "opexMonitor-divircurve";
        String configValue = Convert.toStr(redisService.getCacheObject(configKey));

        if (!configValue.isEmpty()) {
            params.put("range", configValue);
        }

        OpexMonitor opexMonitor = new OpexMonitor();
        //红利曲线检查
        int ict = opexMonitorMapper.queryDivCurveCount(params);
        int dct = opexMonitorMapper.queryDivCurveRatesCount(params);

        opexMonitor.setOpexDate(MapUtils.getString(params, "opexDate"));
        opexMonitor.setOpexName("红利曲线检查");
        opexMonitor.setOpexType("divCurve");
        opexMonitor.setUpdateTime(DateUtils.getCurr_YYYY_MM_DD_HH_MM_SS_SSS());
        if (dct < ict) {
            opexMonitor.setStatus("0");
            opexMonitor.setOpexMsg("红利曲线结果缺失");
        } else {
            opexMonitor.setOpexMsg("红利曲线结果正常");
            opexMonitor.setStatus("1");
        }
        if (opexMonitorMapper.queryOpexMonitor(opexMonitor).size() > 0) {
            opexMonitorMapper.updateOpexMonitor(opexMonitor);
        } else {
            opexMonitorMapper.insertOpexMonitor(opexMonitor);
        }
        if (dct < ict) {
            opexMonitor.setRange(configValue);
            opexMonitorMapper.deleteOpexMonitorDetail(opexMonitor);
            opexMonitorMapper.insertOpexMonitorDetailDivCurve(opexMonitor);
        }
    }

    @Override
    public void checkVlsCurve(Map<String, Object> params) throws SQLException {
        String configKey = Constants.SYS_CONFIG_KEY + "opexMonitor-volsurface";
        String configValue = Convert.toStr(redisService.getCacheObject(configKey));

        if (!configValue.isEmpty()) {
            params.put("range", configValue);
        }

        OpexMonitor opexMonitor = new OpexMonitor();
        //波动率曲面检查
        int ict = opexMonitorMapper.queryVolSurfaceCount(params);
        int dct = opexMonitorMapper.queryVolSurfaceRatesCount(params);

        opexMonitor.setOpexDate(MapUtils.getString(params, "opexDate"));
        opexMonitor.setOpexName("波动率曲面检查");
        opexMonitor.setOpexType("volSurface");
        opexMonitor.setUpdateTime(DateUtils.getCurr_YYYY_MM_DD_HH_MM_SS_SSS());
        if (dct < ict) {
            opexMonitor.setStatus("0");
            opexMonitor.setOpexMsg("波动率曲面结果缺失");
        } else {
            opexMonitor.setOpexMsg("波动率曲面结果正常");
            opexMonitor.setStatus("1");
        }
        if (opexMonitorMapper.queryOpexMonitor(opexMonitor).size() > 0) {
            opexMonitorMapper.updateOpexMonitor(opexMonitor);
        } else {
            opexMonitorMapper.insertOpexMonitor(opexMonitor);
        }
        if (dct < ict) {
            opexMonitor.setRange(configValue);
            opexMonitorMapper.deleteOpexMonitorDetail(opexMonitor);
            opexMonitorMapper.insertOpexMonitorDetailVolSurface(opexMonitor);
        }
    }

    @Override
    public ResponseVo checkSummitFile(Map<String, Object> params) {

        OpexMonitor opexMonitor = new OpexMonitor();
        opexMonitor.setOpexDate(MapUtils.getString(params, "opexDate"));
        opexMonitor.setOpexName("SUMMIT推送检查");
        opexMonitor.setOpexType("summit");
        opexMonitor.setUpdateTime(DateUtils.getCurr_YYYY_MM_DD_HH_MM_SS_SSS());
        // 筛选出监控日期推送的交易
        List<Path> opexDateFiles = filterSummitFile(params);
        boolean summitImportFlag = true; //SUMMIT导入异常标志
        int totalNum = opexDateFiles.size(); // 监控日期推送交易总数
        int failedNum = 0; // 监控日期推送交易失败总数
        // 进行判断文件是否导入成功
        Map map = decideFileIsImport(opexDateFiles, params, summitImportFlag, failedNum);
        List<OpexMonitorDetail> list = (List<OpexMonitorDetail>) map.get("resultList");
        if ((boolean) map.get("flag")) {
            opexMonitor.setStatus("1");
            opexMonitor.setOpexMsg("SUMMIT推送正常");
        } else {
            opexMonitor.setStatus("0");
            opexMonitor.setOpexMsg("SUMMIT推送异常,共推送"+totalNum+"个文件，失败"+map.get("faileNum")+"个文件");
        }
        updateOpexMonitorAndDetail(opexMonitor, list);
        return ResponseVo.success();
    }

    // 筛选出监控日期推送的交易
    public List<Path> filterSummitFile(Map<String, Object> params) {
        Path path = Paths.get(summitFileDir);
        // 获取监控日期的月日
        String opexDate = (String) params.get("opexDate");
//        Calendar cal = Calendar.getInstance();
//        cal.setTime(DateUtils.str2Date_YYYY_MM_DD(opexDate));
//        int mounth = cal.get(Calendar.MONTH) + 1;
//        int day = cal.get(Calendar.DATE);
        String mounth = opexDate.split("-")[1];
        String day = opexDate.split("-")[2];
        // 推送文件名末尾包含的时间戳，进行匹配是否是包含推送日期的，返回所有的监控日期推送的文件
        Pattern pattern = Pattern.compile(".*[^RA]_"+ mounth + day +".*");
        try {
            List<Path> paths = Files.walk(path).filter(p -> {
                //如果不是普通的文件，则过滤掉
                if (!Files.isRegularFile(p)) {
                    return false;
                }
                File file = p.toFile();
                Matcher matcher = pattern.matcher(file.getName());
                return matcher.matches();
            }).collect(Collectors.toList());
            return paths;
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("文件读取错误");
            throw new ServiceException(SummitTranConstants.FILE_IO_ERR);
        }
    }

    // 判断推送文件是否正常导入
    public Map decideFileIsImport(List<Path> opexDateFiles, Map params, boolean summitImportFlag, int failedNum) {
        List<OpexMonitorDetail> opexMonitorDetails = new ArrayList<>();
        String opexDate = (String) params.get("opexDate");
        for(Path item : opexDateFiles) {
            String fileName = item.toFile().getName();
            OpexMonitorDetail opexMonitorDetail = new OpexMonitorDetail();
            opexMonitorDetail.setOpexType("summit");
            opexMonitorDetail.setOpexDate(opexDate);
            opexMonitorDetail.setDetName(fileName);
            opexMonitorDetail.setUpdateTime(DateUtils.getCurr_YYYY_MM_DD_HH_MM_SS_SSS());
            opexMonitorDetail.setDetDate(opexDate);
            if (fileName.startsWith("RA")) {
                opexMonitorDetail.setDetCode("Must");
                String[] fileNameSplit = fileName.split("_");
                if (fileNameSplit.length != 4) {
                    throw new ServiceException(SummitTranConstants.FILE_NAME_ERR);
                }
                Map versionMap = tradeMapper.selectTradeVersionByICode(fileNameSplit[1]);
                int version = Integer.parseInt(fileNameSplit[2]);
                // 进行判断文件的版本号是不是和数据库记录的一致，不一致则为导入失败
                int tradeVersion = versionMap == null ? 0 : (int) versionMap.get("TRADE_VERSION");
                if (version > tradeVersion) {
                    summitImportFlag = false;
                    failedNum ++;
                    opexMonitorDetail.setDetContext("导入失败");
                    opexMonitorDetail.setStatus("0");
                    opexMonitorDetails.add(opexMonitorDetail);
                } else if ( version == tradeVersion){
                    opexMonitorDetail.setDetContext("导入成功");
                    opexMonitorDetail.setStatus("1");
                    opexMonitorDetails.add(opexMonitorDetail);
                } else if ( version < tradeVersion){ // 处理历史版本的交易导入失败情况
                    TsysInterfaceLog tsysInterfaceLog = new TsysInterfaceLog();
                    tsysInterfaceLog.setBusinNo(fileName);
                    tsysInterfaceLog.setOpType(0);
                    tsysInterfaceLog.setActionType(1);
                    TableDataInfo list = remoteLogService.queryLog(tsysInterfaceLog);
                    if (list.getCode() == 500) {
                        logger.error("远程调用导入日志失败");
                        opexMonitorDetail.setDetContext("远程调用导入日志失败");
                        opexMonitorDetail.setStatus("0");
                    } else if (list.getCode() == 200) {
                        if (list.getRows().size() > 0) {
                            summitImportFlag = false;
                            failedNum++;
                            opexMonitorDetail.setDetContext("历史版本交易导入失败");
                            opexMonitorDetail.setStatus("0");
                            opexMonitorDetails.add(opexMonitorDetail);
                        } else {
                            opexMonitorDetail.setDetContext("导入成功");
                            opexMonitorDetail.setStatus("1");
                            opexMonitorDetails.add(opexMonitorDetail);
                        }
                    }
                }
            } else {
                opexMonitorDetail.setDetCode("Option");
                String[] fileNameSplit = fileName.split("_");
                if (fileNameSplit.length != 3) {
                    throw new ServiceException(SummitTranConstants.FILE_NAME_ERR);
                }
                Map versionMap = tradeMapper.selectTradeVersionByICode(fileNameSplit[0]);
                int version = Integer.parseInt(fileNameSplit[1]);
                int tradeVersion = versionMap == null ? 0 : (int) versionMap.get("TRADE_VERSION");
                if (version > tradeVersion) {
                    summitImportFlag = false;
                    failedNum ++;
                    opexMonitorDetail.setDetContext("导入失败");
                    opexMonitorDetail.setStatus("0");
                    opexMonitorDetails.add(opexMonitorDetail);
                } else if ( version == tradeVersion) {
                    opexMonitorDetail.setDetContext("导入成功");
                    opexMonitorDetail.setStatus("1");
                    opexMonitorDetails.add(opexMonitorDetail);
                } else if ( version < tradeVersion) {
                    TsysInterfaceLog tsysInterfaceLog = new TsysInterfaceLog();
                    tsysInterfaceLog.setBusinNo(fileName);
                    tsysInterfaceLog.setOpType(0);
                    tsysInterfaceLog.setActionType(1);
                    TableDataInfo list = remoteLogService.queryLog(tsysInterfaceLog);
                    if (list.getCode() == 500) {
                        logger.error("远程调用导入日志失败");
                        opexMonitorDetail.setDetContext("远程调用导入日志失败");
                        opexMonitorDetail.setStatus("0");
                    } else if (list.getCode() == 200) {
                        if (list.getRows().size() > 0) {
                            summitImportFlag = false;
                            failedNum ++;
                            opexMonitorDetail.setDetContext("历史版本交易导入失败");
                            opexMonitorDetail.setStatus("0");
                            opexMonitorDetails.add(opexMonitorDetail);
                        } else {
                            opexMonitorDetail.setDetContext("导入成功");
                            opexMonitorDetail.setStatus("1");
                            opexMonitorDetails.add(opexMonitorDetail);
                        }
                    }

                }
            }
        }
        Map<String, Object> result = new HashMap<>();
        result.put("resultList", opexMonitorDetails);
        result.put("flag", summitImportFlag);
        result.put("faileNum", failedNum);
        return result;
    }


    @Override
    public void downloadFileZip(OpexMonitorDetail params, HttpServletResponse response) {
        List<OpexMonitorDetail> list = new ArrayList<>();
        try {
            list = opexMonitorMapper.queryOpexMonitorDetailList(params);
        } catch (SQLException e) {
            throw new ServiceException(ErrMsgConstant.QUERY_ERRINFO,e.getMessage());
        }
        List<Map<String, String>> filePaths = new ArrayList<>();
        for (OpexMonitorDetail opexMonitorDetail : list) {
            Map<String, String> fileMap = new HashMap<>();
            fileMap.put("filePath", summitFileDir + opexMonitorDetail.getDetName());
            fileMap.put("fileName", opexMonitorDetail.getDetName());
            filePaths.add(fileMap);
        }
        String zipName = "SUMMITFILE" + params.getOpexDate() + new Date().getTime() + ".zip";
        String zipPath = zipFilePath + zipName;
        CompressUtils.compress(filePaths, zipPath, false);
        File ZipFile = new File(zipPath);
        response = SysUtils.downloadFile(response, ZipFile.getPath(), ZipFile.getName());

    }

    @Override
    public void downloadFile(Map params, HttpServletResponse response) {
        String fileName = (String) params.get("fileName");
        String filePath = summitFileDir + fileName;
        response = SysUtils.downloadFile(response, filePath, fileName);
    }

    @Override
    public ResponseVo checkSpotPrice(Map<String, Object> params) {
        HashMap<String, String> map = new HashMap<>();
        List<OpexMonitorDetail> detailList = new ArrayList<>();
        map.put("endDate", (String) params.get("opexDate"));
        List<Map> list = tequityStructureMapper.queryOpexMonitorInitPrice(map);
        OpexMonitor opexMonitor = new OpexMonitor();
        opexMonitor.setOpexDate(MapUtils.getString(params, "opexDate"));
        opexMonitor.setOpexName("期初价格检查异常");
        opexMonitor.setOpexType("initPrice");
        opexMonitor.setUpdateTime(DateUtils.getCurr_YYYY_MM_DD_HH_MM_SS_SSS());
        if (list.size() == 0) {
            opexMonitor.setStatus("1");
            opexMonitor.setOpexMsg("期初价格设置正常");
        } else {
            opexMonitor.setStatus("0");
            opexMonitor.setOpexMsg("期初价格设置异常");
            detailList = setInitPriceopexMonitorDetail(list, params);
        }
        updateOpexMonitorAndDetail(opexMonitor, detailList);
        return ResponseVo.success();
    }

    @Override
    public ResponseVo checkCalc(Map<String, Object> params) {
        List<OpexMonitorDetail> opexMonitorDetails = new ArrayList<>();
        OpexMonitor opexMonitor = new OpexMonitor();
        opexMonitor.setOpexDate(MapUtils.getString(params, "opexDate"));
        opexMonitor.setOpexName("日终估值检查");
        opexMonitor.setOpexType("endDayValuation");
        opexMonitor.setUpdateTime(DateUtils.getCurr_YYYY_MM_DD_HH_MM_SS_SSS());
        List<Map> list = tradeMapper.checkCalc(params);
        if (list.size() == 0) {
            opexMonitor.setStatus("1");
            opexMonitor.setOpexMsg("日终估值正常");
        } else {
            opexMonitorDetails = setCalcOpexMonitorDetail(list, params);
            opexMonitor.setStatus("0");
            opexMonitor.setOpexMsg("日终估值异常");
        }
        updateOpexMonitorAndDetail(opexMonitor,opexMonitorDetails);
        return ResponseVo.success();
    }

    public List<OpexMonitorDetail> setCalcOpexMonitorDetail(List<Map> list, Map<String, Object> params) {
        List<OpexMonitorDetail> detailList = new ArrayList<>();
        String opexDate = (String) params.get("opexDate");
        for (Map map : list) {
            OpexMonitorDetail opexMonitorDetail = new OpexMonitorDetail();
            opexMonitorDetail.setOpexType("endDayValuation");
            opexMonitorDetail.setOpexDate(opexDate);
            opexMonitorDetail.setUpdateTime(DateUtils.getCurr_YYYY_MM_DD_HH_MM_SS_SSS());
            opexMonitorDetail.setDetDate(opexDate);
            String context = map.get("extTradeId") + "," + map.get("iCode") + "," + map.get("pType") + "," + map.get("calcDate") + "," +
                    map.get("uICode") + "," + map.get("uIName") ;
            opexMonitorDetail.setDetContext(context);
            opexMonitorDetail.setStatus("0");
            opexMonitorDetail.setDetCode((String) map.get("iCode"));
            opexMonitorDetail.setDetName((String) map.get("iCode"));
            detailList.add(opexMonitorDetail);
        }
        return detailList;
    }

    public List<OpexMonitorDetail> setInitPriceopexMonitorDetail(List<Map> list, Map<String, Object> params) {
        List<OpexMonitorDetail> detailList = new ArrayList<>();
        String opexDate = (String) params.get("opexDate");
        for (Map map : list) {
            OpexMonitorDetail opexMonitorDetail = new OpexMonitorDetail();
            opexMonitorDetail.setOpexType("initPrice");
            opexMonitorDetail.setOpexDate(opexDate);
            opexMonitorDetail.setUpdateTime(DateUtils.getCurr_YYYY_MM_DD_HH_MM_SS_SSS());
            opexMonitorDetail.setDetDate(opexDate);
            String context = map.get("EXT_TRADE_ID") + "," + map.get("I_CODE") + "," + map.get("P_TYPE") + "," + map.get("TRADE_DATE") + "," +
                    map.get("U_I_CODE") + "," + map.get("U_I_NAME") + ",NA";
            opexMonitorDetail.setDetContext(context);
            opexMonitorDetail.setStatus("0");
            opexMonitorDetail.setDetCode((String) map.get("I_CODE"));
            opexMonitorDetail.setDetName((String) map.get("I_CODE"));
            detailList.add(opexMonitorDetail);
        }
        return detailList;
    }

    // 更新监控信息，已有就修改，没有就插入，删除所有监控详情，有新的在插入
    public void updateOpexMonitorAndDetail(OpexMonitor opexMonitor, List<OpexMonitorDetail> list ) {
        try {
            if (opexMonitorMapper.queryOpexMonitor(opexMonitor).size() > 0) {
                opexMonitorMapper.updateOpexMonitor(opexMonitor);
            } else {
                opexMonitorMapper.insertOpexMonitor(opexMonitor);
            }
            opexMonitorMapper.deleteOpexMonitorDetail(opexMonitor);
            if (list.size() > 0) {
                opexMonitorMapper.insertOpexMonitorDetailBatch(list);
            }
        } catch (SQLException e) {
            logger.error("更新监控SQL执行失败");
        }

    }
}
